<?php

namespace app\controller;

use support\Request;
use Kingbes\Attribute\Annotation;
use app\common\Tool;
use app\model\Attachment;

#[Annotation(title: "附件组", auth: true)]
class AttachmentController
{
    #[Annotation(title: "查询", view: true)]
    public function query(Request $request)
    {
        // 提交
        if ($request->method() === "POST") {
            // 数据
            $param = $request->all();
            // 查询
            $res = Attachment::where(function ($query) use ($param) {
                if (isset($param["where"])) {
                    $query->withSearch(array_keys($param["where"]), $param["where"]);
                }
            })->order("id", "desc")
                ->paginate([
                    "page" => $param["page"],
                    "list_rows" => $param["limit"],
                ]);
            // 返回
            return json([
                "code" => 0,
                "msg" => "获取成功",
                "count" => $res->total(),
                "data" => $res->toArray()["data"],
            ]);
        }
        // 模板渲染
        return fetch();
    }

    #[Annotation(title: "上传", request: ["POST"])]
    public function upload(Request $request)
    {
        // 提交
        if ($request->method() === "POST") {
            // 检测
            $file = current($request->file());
            if (!$file || !$file->isValid()) {
                return error("找不到文件");
            }
            // 上传
            $data = Tool::uploads($request, "/upload" . "/" . date('Ymd'));
            // 提交
            $res = Attachment::create($data);
            // 返回
            return json(["code" => 0, "msg" => "上传成功", "data" => $res]);
        }
    }

    #[Annotation(title: "编辑", auth: true)]
    public function edit(Request $request)
    {
        // 查找
        $find = Attachment::find($request->get("id"));
        // 赋值模板
        assign("find", $find);
        // 提交
        if ($request->method() === "POST") {
            // 数据
            $data = $request->all();
            // 验证
            if (!isset($data["name"]) || $data["name"] == "") {
                return error(msg: "名称不能为空", data: "name");
            }
            // 更新数据
            $res = Attachment::update($data);
            // 返回
            return success(msg: "编辑成功", data: $res);
        }
        // 输出模板
        return fetch();
    }

    #[Annotation(title: "删除", auth: true)]
    public function del(Request $request)
    {
        // 数据
        $ids = $request->get("ids");
        // 删除
        $destroy = Attachment::destroy($ids);
        // 返回
        if ($destroy) {
            return success("删除成功");
        } else {
            return error(msg: "删除失败", data: $ids);
        }
    }
}
